require "digest/sha1"

class User < ActiveRecord::Base
  has_many :metas
  belongs_to :role
  
  attr_accessor :password_text
  attr_reader :password_text_confirmation
  attr_accessible :name, :password_text, :about, :email, :password_text_confirmation, :role_id
  validates_uniqueness_of :name
  validates_presence_of :name, :password_text, :email
  validates_confirmation_of :password_text
  
  def before_create
    self.password = User.password(self.password_text)
  end
  
  def before_update
    before_create
  end
  
  def after_create
    @password_text = nil
  end
  
  def after_update
    after_create
  end
  
  #禁止删除管理员philong
  before_destroy :dont_destroy_philong
  def dont_destroy_philong
    raise "不能删除管理员——philong" if self.name == 'philong'
  end

  
  def self.login(name, password_text)
    password = password(password_text||"")
    find(:first, :conditions => ["name = ? and password = ?", name, password])
  end
  
  def try_to_login
    User.login(self.name, self.password_text)
  end
  
  private
  def self.password(password_text)
    Digest::SHA1.hexdigest(password_text)
  end
end
